package oaSystem.biz.impl;

import java.util.List;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import oaSystem.Exception.BizRunException;
import oaSystem.biz.RoleBiz;
import oaSystem.entity.Function;
import oaSystem.entity.Role;
import oaSystem.entity.RoleFunction;
import oaSystem.mapper.FunctionMapper;
import oaSystem.mapper.RoleFunctionMapper;
import oaSystem.mapper.RoleMapper;
@Service
public class RoleBizImpl implements RoleBiz {
	@Autowired
	private RoleMapper roleMapper;
	@Autowired
	private FunctionMapper functionMapper;
	@Autowired
	private RoleFunctionMapper roleFunctionMapper;
	@Override
	public Role fetchRoleByRoleId(Integer roleId) {
		Role role = roleMapper.fetchRoleByRoleId(roleId);
		List<Function> functionList = functionMapper.findFunctionByRoleId(roleId);
		role.setFunctionAll(functionList);
		return role;
	}


	@Override
	public List<Role> findAllRole() {
		// TODO Auto-generated method stub
		return roleMapper.findAllRole();
	}
	
	@Transactional(propagation=Propagation.REQUIRED, timeout=60)
	@Override
	public void addRole(Role role) throws BizRunException {
		roleMapper.addRole(role);
		
		//绑定角色的功能
		List<Function> functionList = role.getFunctionAll();
		if(functionList!=null&&functionList.size()>0){
			for (Function function : functionList) {
				//把role关联的function添加到roleFunction表中
				roleFunctionMapper.addRoleFunction(new RoleFunction(null, role, function));
			}
		}
	}
	
	@Transactional(propagation=Propagation.REQUIRED, timeout=60)
	@Override
	public void updateRole(Role role) throws BizRunException {
		roleMapper.updateRole(role);
		
		//把原本角色拥有的功能查询出来
		List<RoleFunction> roleFunctionList = roleFunctionMapper.findRoleFunctionByRoleId(role.getId());
		if(roleFunctionList!=null&&roleFunctionList.size()>0){
			//删除原本角色拥有的功能
			for (RoleFunction roleFunction : roleFunctionList) {
				roleFunctionMapper.deleteRoleFunction(roleFunction.getId());
			}
		}
		//把角色的新功能加入数据库
		List<Function> rfNewList = role.getFunctionAll();
		if(rfNewList!=null&&rfNewList.size()>0){
			for (Function function : rfNewList) {
				roleFunctionMapper.addRoleFunction(new RoleFunction(null, role, function));
			}
		}
		
	}

}
